package jp.ac.u_tokyo.dch.dao.front;

import java.util.List;

import jp.ac.u_tokyo.dch.core.db.CustomPreparedStatement;
import jp.ac.u_tokyo.dch.core.db.DBConnection;
import jp.ac.u_tokyo.dch.core.exceptions.DBException;
import jp.ac.u_tokyo.dch.model.xml.tree.Entry;
import jp.ac.u_tokyo.dch.util.common.CommonDBConnection;
/**
* @version 1.1
*/
public class TreeMenuDao {

	/**
	 * DBコネクションオブジェクト
	 */
	private DBConnection dbconn = null;

	/**
	 * 生成者
	 * @param DBコネクションオブジェクト
	 */
	public TreeMenuDao(DBConnection dbconn){
		this.dbconn = dbconn;
	}

	/**
	 * ツリーメニューテーブルに保存する
	 * @param treeMenu ツリーメニュー
	 * @return 挿入件数
	 * @throws DBException 例外
	 */
	public int insert(String treeMenu) throws DBException {

		CustomPreparedStatement ps1 = null;
		CustomPreparedStatement ps2 = null;
		int result = 0;
		int index = 1;
		try{
			String delQuery = "DELETE FROM tree_menu";
			String query = "INSERT INTO tree_menu (tree) VALUES (?)";

			ps1 = dbconn.prepareStatement(delQuery);
			ps2 = dbconn.prepareStatement(query);
			ps2.setString(index++, treeMenu);
			ps1.executeUpdate();
			result = ps2.executeUpdate();
		}catch(DBException dbe){
			throw dbe;
		}finally{
			CommonDBConnection.closeResource(ps1);
			CommonDBConnection.closeResource(ps2);
		}
		return result;
	}


	/**
	 * ツリーメニューテーブルに保存する
	 * @param treeMenu ツリーメニュー
	 * @return 挿入件数
	 * @throws DBException 例外
	 */
	public int insert(List<Entry> treeList) throws DBException {

		CustomPreparedStatement ps1 = null;
		CustomPreparedStatement ps2 = null;
		int result = 0;
		int index = 1;
		try{
			String delQuery = "DELETE FROM tree_menu";
			String query = "INSERT INTO tree_menu (tree) VALUES (?)";

			ps1 = dbconn.prepareStatement(delQuery);
			ps2 = dbconn.prepareStatement(query);
			ps2.setString(index++, convertTreeMenu(treeList));
			ps1.executeUpdate();
			result = ps2.executeUpdate();
		}catch(DBException dbe){
			throw dbe;
		}finally{
			CommonDBConnection.closeResource(ps1);
			CommonDBConnection.closeResource(ps2);
		}
		return result;
	}


	private String convertTreeMenu(List<Entry> treeList) {

		StringBuilder tree = new StringBuilder();
		tree.append("<rtree>");
		for (Entry entry : treeList) {
			tree.append(entry.print());
		}
		tree.append("</rtree>");

		return tree.toString();
	}
}




